package com.tmall.testgen.transfer.server;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.tmall.testgen.common.ConnectionCommond;
import com.tmall.testgen.common.socket.SocketInfoListener;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class TransferServer {
    
    
	public static ExecutorService pool = Executors.newFixedThreadPool(5);
	public static volatile boolean start = true;
	
	
	public static void main(String[] args) throws Exception {
	    startServer() ;
    }
	public static void startServer() throws Exception {
		ServerSocket	ss = new ServerSocket(ConnectionCommond.Transfer_Server_Port);
		while (start) {
			Socket socket = ss.accept();
			SocketHandler socetHandler=new SocketHandler(socket);
			pool.execute(socetHandler);
		}
		ss.close();
				
	}
	
	 static class SocketHandler implements Runnable{
		 private  Object syn=new Object();
		public OutputStream out;
		private Socket socket;
		 public SocketHandler(Socket s){
			 socket=s;
			
		 }
		 
		public  void run() {
			 try {
				out = socket.getOutputStream();
				
				new SocketInfoListener(socket,syn,new TransferServerReceiveObjectHandler(out)).startListener();
				
				//客户端关闭
				synchronized (syn) {
					syn.wait();
				}
				
				System.out.println("连接关闭1");
				out.close();
				socket.close();
			} catch (Exception e) {
			    StringWriter sw = new StringWriter();  
                PrintWriter pw = new PrintWriter(sw);  
                e.printStackTrace(pw);  
                System.out.println(sw.toString());
			    e.printStackTrace();
				try {
					out.close();
					socket.close();
					System.out.println("连接关闭2");
				} catch (IOException e1) {
					//e1.printStackTrace();
				}
				
				//e.printStackTrace();
			}
			
		 }
	 }
	
}
